<template>
    <div style="padding: 20px;margin-top:20px;margin-bottom: 20px;">
        <page-main title="基础设置">
            <template #title>
                <div class="btn-box">
                    <el-button @click="router.go(-1)">返回</el-button>
                    <el-button @click="exportExcel" v-loading="loading">导出</el-button>
                    <el-button @click="updateStatus">{{ dataForm.enabled ? '停用' : '启用' }}</el-button>
                    <el-button type="primary" @click="toEdit">编辑</el-button>
                </div>
            </template>
            <el-form :model="dataForm" ref="formRef" :inline="false" label-width="140px">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="标准名称：" prop="standardName">

                            {{ dataForm.standardName }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="标准类型：" prop="standardTypeCode">
                            {{ dataForm.standardTypeName }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="标准编码：" prop="standardCode">
                            {{ dataForm.standardCode }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="关联费用类型：" prop="feeTypeDTOList">

                            <el-select v-model="dataForm.feeTypeDTOList" filterable clearable style="width:100%"
                                multiple disabled>
                                <el-option v-for="item in relationOptions" :key="item.typeCode" :label="item.typeName"
                                    :value="item.typeCode" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="同行人标准：" prop="companionStandard">

                            <el-select v-model="dataForm.companionStandard" clearable style="width:100%" disabled>
                                <el-option v-for="item in TOHORO_OPTIONS" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="超标限制：" prop="afterExceed">
                            <el-select v-model="dataForm.afterExceed" clearable style="width:100%" disabled>
                                <el-option v-for="item in LIMIT_OPTIONS" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="状态：" prop="enabled">
                            <p v-if="dataForm.enabled" style="color:green;margin:0">启用</p>
                            <p v-else style="color:red;margin:0">禁用</p>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="创建时间：" prop="createTime">

                            {{ dataForm.createTime }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="创建人：" prop="createUser">
                            {{ dataForm.createUser }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="备注：" prop="remark" style="color:#545454">
                            {{ dataForm.remark }}
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </page-main>
        <page-main title="标准设置">

            <el-table :data="tableData" style="width: 100%">
                <el-table-column type="index" width="80" label="序号" />
                <el-table-column prop="targetArea" label="适用范围">
                    <template #default="scope">

                        <div class="select-con">
                            <p v-if="!scope.row.matchText">请选择适用范围，默认全员适用</p>
                            <p class="scope" v-else>{{ scope.row.matchText }}</p>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="targetArea" label="适用职级" show-overflow-tooltip>
                    <template #default="scope">
                        <div class="select-con">
                            <p v-if="!scope.row.targetRank">请选择适用职级，默认全员适用</p>
                            <p class="scope" v-else>{{ scope.row.targetRankText }}</p>
                        </div>


                    </template>
                </el-table-column>
                <el-table-column prop="address" label="城市（目的地）">
                    <template #default="scope">
                        <div class="select-con">
                            <p v-if="!scope.row.areaText">请选择城市，默认不限</p>
                            <p class="scope" v-else>{{ scope.row.areaText }} </p>
                        </div>
                    </template>
                </el-table-column>

                <template v-if="tableTypeCoulums[dataForm.standardTypeCode]">
                    <!-- 轮船、飞机、火车 -->
                    <el-table-column :label="tableTypeCoulums[dataForm.standardTypeCode].label">

                        <template #default="scope">

                            <el-checkbox-group v-model="scope.row.seatClass">
                                <el-checkbox :label="item.configValue"
                                    v-for="(item, index) in tableTypeCoulums[dataForm.standardTypeCode].options"
                                    :key="index" disabled>{{
                                    item.configValueName
                                    }}</el-checkbox>>
                            </el-checkbox-group>
                        </template>
                    </el-table-column>
                </template>
                <template v-if="['customize', 'allowance', 'hotel', 'mileage'].includes(dataForm.standardTypeCode)">
                    <el-table-column label="日期">
                        <template #default="scope">
                            <el-select v-model="scope.row.dateCategoryId" style="width:100%" disabled>
                                <el-option v-for="item in dateOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </template>
                    </el-table-column>
                </template>
                <template v-if="['customize', 'allowance'].includes(dataForm.standardTypeCode)">
                    <el-table-column label="金额（元/天）">
                        <template #default="scope">
                            <el-input v-model="scope.row.amountLimit" placeholder="请输入" type="number" disabled />
                        </template>
                    </el-table-column>
                </template>
                <template v-if="['hotel'].includes(dataForm.standardTypeCode)">
                    <el-table-column label="单人金额（元/天）">
                        <template #default="scope">
                            <div class="flex">
                                <span>&lt;=</span>
                                <el-input v-model="scope.row.singleLimit" type="number" placeholder="请输入" disabled />
                                <span class="unit">元</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="双人金额（元/天）">
                        <template #default="scope">
                            <div class="flex">
                                <span>&lt;=</span>
                                <el-input v-model="scope.row.doubleLimit" type="number" placeholder="请输入" disabled />
                                <span class="unit">元</span>
                            </div>
                        </template>
                    </el-table-column>
                </template>
                <template v-if="['mileage'].includes(dataForm.standardTypeCode)">
                    <el-table-column label="里程单价">
                        <template #default="scope">
                            <span>&lt;=</span>
                            <el-input v-model="scope.row.amountLimit" type="number" placeholder="请输入" disabled />
                            <span class="unit">元/公里</span>
                        </template>
                    </el-table-column>
                </template>

            </el-table>
        </page-main>

    </div>
</template>
<script  setup name="Standard">
import { reactive } from 'vue'
import { STATUS_LIST, LIMIT_OPTIONS, TOHORO_OPTIONS } from '../Common/config'
import { statusText } from '@/util/index'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'
import { useRoute, useRouter } from 'vue-router'
import { downloadFile } from '@/util/downFile'
import dayjs from 'dayjs'
const dataForm = ref({
    feeTypeDTOList: [],
    companionStandard: '',
    standardTypeCode: '',
    standardName: '',
    afterExceed: ''
})

const loading = ref(false)

const router = useRouter()

const route = useRoute()

const tableData = ref([])

const dateOptions = ref([
    { label: '不限', value: null },
])

const tableTypeCoulums = ref({
    'airplane': { label: '飞机舱位', options: [] },
    'train': { label: '火车坐席', options: [] },
    'ship': { label: '轮船舱位', options: [] },
})

const dialogVisibleCity = ref(false)

const relationOptions = ref([]) // 关联费用类型

const formRef = ref(null)


onMounted(() => {
    const { id } = route.query
    getFeeTypeList(id)

    getDateTypeList()

})

const getDetail = (id) => {
    api.feeConfig.feeStandardDetail({ id }).then(res => {
        // console.log(res)
        try {
            let listFeeType = []
            let obj = { ...res }
            queryShipping(res.standardTypeCode, false)
            res.feeTypeDTOList.forEach(item => {
                listFeeType.push(item.typeCode)
            })
            res.configDTOList.forEach(item => {
                let configContent = item.configContent && JSON.parse(item.configContent)
                console.log(item['matchTarget'], 8888)
                item['matchTarget'] = item['matchTarget'] && JSON.parse(item['matchTarget'])
                item['targetArea'] = item['targetArea'] && JSON.parse(item['targetArea'])
                item['targetRank'] = item['targetRank'] && JSON.parse(item['targetRank'])
                item['matchText'] = item['matchTarget']['matchText']
                item['areaText'] = item['targetArea']['areaText']
                item['targetRankText'] = item['targetRank'] && item['targetRank']['targetRankText']
                for (let k in configContent) {
                    item[k] = configContent[k]
                }
            })
            console.log(res.configDTOList, 777)
            obj.createTime = dayjs(obj['createTime']).format('YYYY-MM-DD');
            obj['feeTypeDTOList'] = listFeeType
            dataForm.value = obj
            tableData.value = res.configDTOList

        } catch (error) {
            console.log(error, 'error')

        }

    })

}


// 获取费用类型
const getFeeTypeList = (id) => {
    const params = {
        pageNum: 1,
        pageSize: 10000,
        enabled: true
    }
    api.feeConfig.feeTypeList(params).then(res => {
        relationOptions.value = res.list
        getDetail(id)
    })

}

// 获取日期类型列表数据
const getDateTypeList = () => {
    const parms = {
        pageNum: 1,
        pageSize: 1000,
    }
    api.feeConfig.dateTypeList(parms).then(res => {
        const { list, total } = res
        list.forEach(item => {
            item['label'] = item.categoryName
            item['value'] = item.id
        })
        dateOptions.value = [...dateOptions.value, ...list]

    })

}

// 根据费用类型查询
const queryShipping = (val) => {
    if (tableTypeCoulums.value[val] && tableTypeCoulums.value[val]['options'].length > 0) return
    api.feeConfig.feeStandardTypeQuery({ type: val }).then(res => {
        console.log(res)
        if (res.length > 0) {
            try {
                tableTypeCoulums.value[val]['options'] = res
                console.log(tableTypeCoulums.value[val])
            } catch (error) {

            }

        }
    })

}
const updateStatus = () => {
    const { enabled, id } = dataForm.value
    let text = enabled ? '停用' : '启用'
    ElMessageBox.confirm(`您确定要进行${text}操作吗?`, "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        api.feeConfig.feeStandardUpdateStatus({ id: id, enabled: enabled ? false : true }).then((res) => {
            getDetail(id);
            ElMessage.success("操作成功");
        });
    });
};
const toEdit = () => {
    const { id } = dataForm.value
    router.push({
        name: 'standardEdit',
        query: {
            type: 'edit',
            id
        }
    })

}
// 导出
const exportExcel = (row) => {
    loading.value = true

    api.feeConfig.feeStandarExport().then((res) => {
        console.log(res)
        downloadFile(res, '费用标准详情', 'xlsx')
        ElMessage({
            type: 'success',
            message: '导出成功!'
        });
        loading.value = false
    })
}


</script>
<style lang="scss" scoped>
.select-con p {
    color: #0049ad;
    cursor: pointer;
}

.flex {
    display: flex;

    span {
        display: inline-block;
        width: 40px;
    }
}
</style>
